package leetcode.sword;

public class Solution29 {

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(spiralOrder(matrix));
    }

    public static int[] spiralOrder(int[][] matrix) {
        int rowh = matrix.length;
        if(rowh==0) return new int[0];
        int colh = matrix[0].length;
        if(colh==0) return new int[0];
        int rowl = 0, coll = 0;
        int[] res = new int[rowh*colh];
        int count = 0;
        while(true){
            //右
            for(int i=coll;i<colh;i++,count++){
                res[count]= matrix[rowl][i];
            }
            if(++rowl==rowh) break;
            //下
            for(int i=rowl;i<rowh;i++,count++){
                res[count]= matrix[i][colh-1];
            }
            if(--colh==coll) break;
            //左
            for(int i=colh-1;i>=coll;i--,count++){
                res[count]= matrix[rowh-1][i];
            }
            if(--rowh==rowl) break;
            //上
            for(int i=rowh-1;i>=rowl;i--,count++){
                res[count]= matrix[i][coll];
            }
            if(++coll==colh) break;
        }
        return res;
    }
}